﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.AuditLogging.LogEntry;
using System.Security.Cryptography;
using PSE.AuditLogging.Common.Exception;

namespace PSE.AuditLogging.StorageService.Instance
{
    internal class LogEntryPackageValidator
    {
        private static byte[] hashComplement = { 10, 14, 23, 56, 1, 0, 99, 14 };

        /// <summary>
        /// Validar um pacote, validando se as propriedade estão preenchidas e se a assinatura é válida
        /// </summary>
        /// <param name="packageEntry"></param>
        /// <returns></returns>
        internal static void Validate(LogEntryPackage packageEntry)
        {
            try
            {
                #region validacoes do parametro de entrada

                if (packageEntry == null)
                    throw new ArgumentNullException("packageEntry");

                if (packageEntry.Body == null)
                    throw new ArgumentNullException("packageEntry.Body");

                if (string.IsNullOrEmpty(packageEntry.BodySignature))
                    throw new InvalidSignatureException("The package signature cannot be null");

                #endregion

                #region Verificacao da assinatura do dado

                PSE.Framework.Serialization.BinarySerializer ser = new PSE.Framework.Serialization.BinarySerializer();
                SHA384Managed hasher = new SHA384Managed();

                byte[] body = ser.Serialize(packageEntry.Body);
                byte[] hashData = new byte[body.Length + hashComplement.Length];

                body.CopyTo(hashData, 0);
                hashComplement.CopyTo(hashData, body.Length);

                byte[] bSign = hasher.ComputeHash(hashData);

                if (Convert.ToBase64String(bSign) != packageEntry.BodySignature)
                    throw new InvalidSignatureException("The package signature is invalid");

                #endregion
            }
            catch (InvalidSignatureException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new InvalidLogEntryPackageException(ex);
            }
        }
    }
}
